<?php


namespace App\Services\Admin;


use App\Http\Controllers\Api\RemoteApiRoute;
use App\Models\Task;
use Illuminate\Support\Facades\Http;
use MongoDB\BSON\ObjectId;

class TaskService
{
    protected $task;

    public function __construct(Task $task)
    {
        $this->task = $task;
    }

    /**
     * 获取列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function getTaskInfo($params)
    {
        $where = [];
        $task = Task::where($where)->orderBy('create_time','desc')->get();
        $total = Task::where($where)->count();

        foreach ($task as $item) {
            $item->create_time = date('Y-m-d H:i:s', $item->create_time);
        }
        return success('获取成功！', ['items' => $task, 'total' => $total]);
    }

    /**
     * 获取列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function taskProduct($params)
    {
        $where = ['_id' => new ObjectId($params['_id'])];
        $task = Task::where($where)->first();
        if ($task->get_product_status !== 'wait') {
            return Error('该任务正在获取中或已获取完毕！');
        }

        //同时只能有一个任务进行中
        $exist = Task::where('get_product_status', 'pending')->first();
        if ($exist){
            return Error('当前已有任务正在处理中，请等待结束后再次请求！');
        }

        $params['client_task_id'] = $task->_id;
        $params['cat_id'] = $task->cat_id;
        $params['domain_id'] = $task->domain_id;
        $params['sales_rank_range'] = $task->sales_rank_range;
        $params['counts'] = $task->counts;
        $params['recent_update'] = $task->recent_update;
        $params['client_create_time'] = $task->create_time;

        //请求远程服务器抓取产品信息
        $protocol = request()->getScheme() . '://';
        $params['host'] = $protocol . request()->getHttpHost();
        $url = env('REMOTE_API_URL') . RemoteApiRoute::TASK_PRODUCT;
        $response = Http::post($url, $params);
        if ($response->ok()) {
            $res = $response->json();
            if ($res['code'] == 0) {
                Task::where($where)->update(['get_product_status' => 'pending']);
                return Success($res['message'], $res);
            } else {
                return Error($res['message'], $res);
            }
        } else {
            return Error($response->reason());
        }
    }

    public function taskSelect(){
        $task = Task::orderBy('create_time','desc')->limit(20)->get();
        foreach ($task as $item){
            $title = date('Y-m-d').'-'.$item->cat_name.'-'.$item->counts;
            $arr[] = [
                'name' => $title,
                'value' => $item->_id
            ];
        }
        return success('获取成功！', $arr);
    }
}
